﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace PloobsEngine.SceneControl
{
    public class RestoreDepth
    {
        public RestoreDepth(EngineStuff engine , bool useFloatBuffer)
        {
            this.engine = engine;
            this.restore = EngineStuff.InternalContentManager.GetAsset<Effect>("RestoreDepth");
            if (useFloatBuffer)
                target = EngineStuff.GetDefaultBuffer(SurfaceFormat.HalfVector4);
            else
                target = EngineStuff.GetDefaultColorBuffer();            
        }        
        private RenderTarget2D target;
        private Effect restore;
        private EngineStuff engine;

        public void PerformForwardPass(Texture2D combined, Texture2D depth, QuadRender render)
        {            

            EngineStuff.GraphicsDevice.SetRenderTarget(0, target);

            EngineStuff.GraphicsDevice.RenderState.DepthBufferEnable = true;
            EngineStuff.GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
            
            restore.Begin();
            {
                restore.Techniques["Technique2"].Passes[0].Begin();                                
                restore.Parameters["DepthTexture"].SetValue(depth);
                restore.Parameters["halfPixel"].SetValue(EngineStuff.HalfPixel);                
                restore.Parameters["ColorTexture"].SetValue(combined);                                
                render.Render(Vector2.One * -1, Vector2.One);
                restore.Techniques["Technique2"].Passes[0].End();
            }
            restore.End();

        }
               

        //public void PrepareForForwardPass(Texture2D combined , Texture2D depth, Engine.SceneControl.Scene.DefRender.QuadRender render)
        //{
        //    EngineStuff.GraphicsDevice.SetRenderTarget(0, target);
        //    SpriteBatch spriteBatch = engine.SpriteBatch;
        //    spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.None);
        //    EngineStuff.GraphicsDevice.RenderState.DepthBufferEnable = true;
        //    restore.Parameters["DepthTexture"].SetValue(depth);
        //    restore.Begin();
        //    foreach (EffectPass pass in restore.CurrentTechnique.Passes)
        //    {
        //        pass.Begin();
        //        spriteBatch.Draw(combined, Vector2.Zero, Color.White);
        //        pass.End();
        //    }
        //    restore.End();
        //    spriteBatch.End();            
        //}

        public Texture2D EndForwardPass()
        {
            EngineStuff.GraphicsDevice.SetRenderTarget(0, null);
            return target.GetTexture();
        }
    }
}
